package cn.guetzjb.sys.service.impl;

import cn.guetzjb.sys.domain.*;
import cn.guetzjb.sys.mapper.SysUserMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.guetzjb.sys.service.SysDeptService;
import cn.guetzjb.sys.mapper.SysDeptMapper;
import com.github.yulichang.query.MPJLambdaQueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author admin
 * @description 针对表【sys_dept(部门表)】的数据库操作Service实现
 * @createDate 2023-12-22 16:18:23
 */
@Service
@RequiredArgsConstructor
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept>
        implements SysDeptService {

    private final SysUserMapper userMapper;

    @Override
    public List<SysDept> getTreeDeptList() {
        List<SysDept> list = baseMapper.selectList(Wrappers.lambdaQuery());
        List<SysDept> root = new ArrayList<>();
        Map<Long, SysDept> map = new HashMap<>();
        for (SysDept sysDept : list) {
            map.put(sysDept.getDeptId(), sysDept);
            if (sysDept.getParentId() == 0L) {
                root.add(sysDept);
            }
        }
        for (SysDept sysDept : list) {
            if (sysDept.getParentId() != 0L) {
                SysDept fa = map.get(sysDept.getParentId());
                fa.getChildren().add(sysDept);
            }
        }
        return root;
    }

    @Override
    public Page<SysUser> getUserListByDeptId(Page<SysUser> page, Long deptId) {
        MPJLambdaWrapper<SysUser> wrapper = new MPJLambdaWrapper<>();
        wrapper.select(SysUser::getUserName, SysUser::getNickName, SysUser::getEmail, SysUser::getPhonenumber)
                .select(SysDept::getDeptId)
                .leftJoin(SysUserRole.class, SysUserRole::getUserId, SysUser::getUserId)
                .leftJoin(SysRole.class, SysRole::getRoleId, SysUserRole::getRoleId)
                .leftJoin(SysRoleDept.class, SysRoleDept::getRoleId, SysRole::getRoleId)
                .leftJoin(SysDept.class, SysDept::getDeptId, SysRoleDept::getDeptId)
                .selectAssociation(SysDept.class, SysUser::getDept);
        if (deptId != -1) {
            wrapper.eq(SysDept::getDeptId, deptId);
        }
        return userMapper.selectJoinPage(page, SysUser.class, wrapper);
    }

}




